/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mz2d.map;

import java.io.BufferedReader;
import java.io.FileReader;

/**
 *
 * @author Laptop
 */
public class MapStreamer {

    private int[] tiles;
    private int tileWidth;

    public MapStreamer() {
        try {
            tiles = new int[0];
            BufferedReader br = new BufferedReader(new FileReader("./data/map.txt"));

            String line = "";
            int count = 0;
            while ((line = br.readLine()) != null) {

                String[] tileSplit = line.split(" ");

                for (int i = 0; i < tileSplit.length; i++) {
                    add(Integer.parseInt(tileSplit[i]));
                    count++;
                }

                tileWidth = count;
                count = 0;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void add(int tileData) {
        int found = -1;
        for (int i = 0; i < tiles.length; i++) {
            if (tiles[i] == -1) {
                found = i;
            }
        }

        if (found != -1) {
            tiles[found] = tileData;
            return;
        }

        int[] tmpTiles = tiles;
        tiles = new int[tmpTiles.length + 1];

        System.arraycopy(tmpTiles, 0, tiles, 0, tmpTiles.length);
        tiles[tmpTiles.length] = tileData;
    }

    public MapBuffer getBuffer(int x, int y, int w, int h) throws MapException {
        if (x < 0 || y > (tiles.length / tileWidth)) {
            throw new MapException("x < 0 || y > tH | Outofbounds");
        }
        Tile[] tmpTiles = new Tile[w * h];

        /** copy first row */
        for (int i = 0; i < h; i++) {
            for (int i2 = 0; i2 < w; i2++) {
                tmpTiles[(w * i) + i2] = new Tile();
                int tPos = (x + i2) + (i * tileWidth) + (y * tileWidth);
                if (tPos >= tiles.length) {
                    /** Out of map **/
                    tmpTiles[(w * i) + i2].setType(-1);
                } else {
                    tmpTiles[(w * i) + i2].setType(tiles[tPos]);
                }
            }
        }

        MapBuffer mb = new MapBuffer(tmpTiles, w, h);
        return mb;
    }

    public int getTileWidth() {
        return tileWidth;
    }

    public int[] getTiles() {
        return tiles;
    }
}
